package com.jingdianjichi.subject.infra.basic.service.impl;

import com.jingdianjichi.subject.infra.basic.entity.SubjectInfoEs2;
import com.jingdianjichi.subject.infra.basic.esRepo.SubjectEsRepository;
import com.jingdianjichi.subject.infra.basic.service.SubjectEsService2;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 董代恒
 * @version 1.0
 */
@Service
@Slf4j
public class SubjectEsService2Impl implements SubjectEsService2 {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private SubjectEsRepository subjectEsRepository;

    /**
     * 创建索引
     */
    @Override
    public void createIndex() {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(SubjectInfoEs2.class);
        indexOperations.create();
        Document mapping = indexOperations.createMapping();
        indexOperations.putMapping(mapping);
    }

    /**
     * 添加文档
     */
    @Override
    public void addDoc() {
        List<SubjectInfoEs2> list = new ArrayList<SubjectInfoEs2>();
        list.add(new SubjectInfoEs2(1L, "redis是什么", "redis是一种缓存", "jichi", new Date()));
        list.add(new SubjectInfoEs2(2L, "mysql是什么", "mysql是数据库", "jichi", new Date()));
        subjectEsRepository.saveAll(list);
    }

    /**
     *
     */
    @Override
    public void find() {
        Iterable<SubjectInfoEs2> all = subjectEsRepository.findAll();

        for (SubjectInfoEs2 subjectInfoEs2 : all) {
            log.info("subjectInfoEs2 {}", subjectInfoEs2);
        }
    }

    /**
     *
     */
    @Override
    public void search() {
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("subjectName", "redis")).build();

        SearchHits<SubjectInfoEs2> search = elasticsearchRestTemplate.search(nativeSearchQuery, SubjectInfoEs2.class);

        List<SearchHit<SubjectInfoEs2>> searchHits = search.getSearchHits();

        for (SearchHit<SubjectInfoEs2> searchHit : searchHits) {
            log.info("subjectInfoEs {}", searchHit);
        }
    }
}
